// 是个插件，使用的时候要install
const LazyLoad = {
    install(Vue, options) {
        let defaultPic = options.default;
        Vue.directive('lazy', {
            bind(el, binding) {
                LazyLoad.init(el, binding.value, defaultPic);
            },
            inserted(el) {
                // 兼容处理
                if ('IntersectionObserver' in window) {
                    // 新API。异步函数，要比监听scroll好得多
                    LazyLoad.observe(el);
                } else {
                    LazyLoad.listenScroll(el);
                }
            }
        })
    },

    // 初始化
    init(el, value, defaultSrc) {
        // 设置真实路径到data-src上。
        el.setAttribute('data-src', value);
        // 设置真实的为加载图
        el.setAttribute('src', defaultSrc);
    },
    // 监听对象
    observe(el) {
        const ob = new IntersectionObserver(entries => {
            let realSrc = el.dataset.src;
            // 如果出现在视口了
            if (entries[0].isIntersecting && realSrc) {
                el.src = realSrc;
                el.removeAttribute('data-src');
                // 停止监听
                ob.unobserve(el);
            }
        });
        ob.observe(el);
    },
    // 监听scroll
    listenScroll(el) {
        let handler = LazyLoad.throttle(LazyLoad.load, 300);
        LazyLoad.load(el);
        // 增加scroll监听
        window.addEventListener('scroll', () => {
            handler(el);
        })
    },
    // 加载方法
    load(el) {
        let windowHeight = document.documentElement.clientHeight;
        let elTop = el.getBoundingClientRect().top;
        let elbtm = el.getBoundingClientRect().bottom;

        let realSrc = el.dataset.src;
        if (elTop - windowHeight < 0 && elbtm > 0) {
            el.src = realSrc;
            el.removeAttribute('data-src');
        }
    },
    // 节流函数
    throttle(fn, delay = 500) {
        let timer;

        return function (...args) {
            if (timer) return;
            const context = this;

            timer = setTimeout(() => {
                fn.apply(context, args);
                timer = null;
            }, delay);
        }
    }
}
export default LazyLoad;